package xyz.chaobei.mall.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import xyz.chaobei.common.api.CommonResult;
import xyz.chaobei.mall.model.UmsAdminModel;
import xyz.chaobei.mall.model.UmsMenuModel;
import xyz.chaobei.mall.model.UmsRoleModel;
import xyz.chaobei.mall.pojo.UmsAdminSaveAO;
import xyz.chaobei.mall.pojo.UmsAdminPageAO;
import xyz.chaobei.mall.service.UmsAdminRoleRelationService;
import xyz.chaobei.mall.service.UmsAdminService;
import xyz.chaobei.mall.service.UmsMenuService;
import xyz.chaobei.mall.service.UmsRoleService;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台用户请求控制层
 *
 * @author mrc
 * @since 2020-10-11 20:39:11
 */
@Api(tags = "ApiUmsAdminController", description = "后台用户")
@RestController
@RequestMapping("/umsAdmin")
@Validated
@Slf4j
public class ApiUmsAdminController {

    @Autowired
    private UmsAdminService umsAdminService;

    @Autowired
    private UmsRoleService umsRoleService;

    @Autowired
    private UmsMenuService umsMenuService;

    @Autowired
    private UmsAdminRoleRelationService umsAdminRoleRelationService;
    /**
     * <p>拉取用户基本信息
     *
     * @param principal 用户信息
     * @return xyz.chaobei.common.api.CommonResult
     * @author: <a href='mailto:maruichao52@gmail.com'>MRC</a>
     * @since 2021/3/12
     **/
    @GetMapping("/info")
    @ApiOperation("拉取用户信息")
    public CommonResult pullUserInfo(Principal principal) {

        String userName = principal.getName();
        log.info("pullUserInfo[前端拉取用户信息] userName={}", userName);

        UmsAdminModel model = umsAdminService.findUserByUserName(userName);
        log.info("pullUserInfo[前端拉取用户信息] model={}", JSON.toJSONString(model));

        List<UmsRoleModel> roles = umsRoleService.queryNormalRoleByUserId(model.getId());
        log.info("pullUserInfo[前端拉取用户信息] roles={}", JSON.toJSONString(roles));

        List<String> roleNames = roles.stream().map(UmsRoleModel::getName).collect(Collectors.toList());
        List<Integer> roleIds = roles.stream().map(UmsRoleModel::getId).collect(Collectors.toList());

        List<UmsMenuModel> menus = umsMenuService.queryMenuListByRoleIds(roleIds);

        log.info("pullUserInfo[前端拉取用户信息] menus={}", JSON.toJSONString(menus));

        Map<String, Object> data = new HashMap<>();
        data.put("username", model.getUsername());
        data.put("roles", roleNames);
        data.put("menus", menus);

        return CommonResult.success(data);
    }

    /**
     * <p>查询用户开通的角色ID
     * <p>author: <a href='mailto:maruichao52@gmail.com'>MRC</a>
     *
     * @param userId 用户ID
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2021/3/17
     **/
    @GetMapping("/role/{userId}")
    @ApiOperation("查询用户开通的角色ID")
    public CommonResult adminRole(@PathVariable("userId") @NotNull @ApiParam("用户ID") Integer userId) {

        List<UmsRoleModel> roles = umsRoleService.queryNormalRoleByUserId(userId);
        log.info("pullUserInfo[前端拉取用户信息] roles={}", JSON.toJSONString(roles));

        List<Integer> roleIds = roles.stream().map(UmsRoleModel::getId).collect(Collectors.toList());
        return CommonResult.success(roleIds);
    }

    /**
     * <p>
     * <p>author: <a href='mailto:maruichao52@gmail.com'>MRC</a>
     *
     * @param userId  用户ID
     * @param roleIds 角色IDS
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2021/3/17
     **/
    @PutMapping("/role/{userId}")
    @ApiOperation("修改用户的角色")
    public CommonResult updateAdminRole(@PathVariable("userId") @NotNull @ApiParam("用户ID") Integer userId, @RequestBody List<Integer> roleIds) {

        boolean isUpdate = umsAdminRoleRelationService.updateAdminRole(userId,roleIds);

        return CommonResult.result(isUpdate);
    }

    /**
     * <p>查询所有后台用户
     * <p>author: mrc
     *
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2020-10-11 20:39:11
     **/
    @ApiOperation("查询所有后台用户")
    @GetMapping("/")
    public CommonResult getAll() {

        List<UmsAdminModel> allList = umsAdminService.findAll();
        return CommonResult.success(allList);
    }

    /**
     * <p>查询单个用户信息
     * <p>author: <a href='mailto:maruichao52@gmail.com'>MRC</a>
     *
     * @param id 查询ID
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2021/3/12
     **/
    @ApiOperation("查询单个后台用户")
    @GetMapping("/{id}")
    public CommonResult getOne(@PathVariable("id") Integer id) {
        UmsAdminModel result = umsAdminService.findOne(id, true);
        return CommonResult.success(result);
    }

    /**
     * <p>默认分页请求后台用户
     * <p>author: mrc
     *
     * @param pageAO 分页入参查询参数
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2020-10-11 20:39:11
     **/
    @ApiOperation("默认分页请求后台用户")
    @PostMapping("/page")
    public CommonResult paging(@RequestBody @ApiParam("分页入参查询参数") UmsAdminPageAO pageAO) {

        Page<UmsAdminModel> allList = umsAdminService.findPage(pageAO);
        return CommonResult.success(allList);
    }

    /**
     * <p>保存一个后台用户
     * <p>author: mrc
     *
     * @param params 保存入参信息
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2020-10-11 20:39:11
     **/
    @ApiOperation("保存一个后台用户")
    @PostMapping("/")
    public CommonResult save(@RequestBody @Valid @ApiParam("保存入参信息") UmsAdminSaveAO params) {

        boolean isSave = umsAdminService.save(params);
        return CommonResult.result(isSave);
    }


    /**
     * <p>修改一个后台用户
     * <p>author: mrc
     *
     * @param id     被修改的ID 信息
     * @param params 被修改的信息
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2020-10-11 20:39:11
     **/
    @ApiOperation("修改一个后台用户")
    @PutMapping("/{id}")
    public CommonResult update(@PathVariable("id") @ApiParam("被修改的ID") Integer id, @Valid @RequestBody @ApiParam("被修改的信息") UmsAdminSaveAO params) {

        boolean isUpdate = umsAdminService.updateById(params, id);
        return CommonResult.result(isUpdate);
    }

    /**
     * <p>删除一个后台用户
     * <p>author: mrc
     *
     * @param id 被删除的ID 信息
     * @return xyz.chaobei.common.api.CommonResult
     * @since 2020-10-11 20:39:11
     **/
    @DeleteMapping("/{id}")
    @ApiOperation("删除一个后台用户")
    public CommonResult delete(@Valid @NotNull @PathVariable("id") @ApiParam("被删除的ID") Integer id) {

        boolean isDelete = umsAdminService.deleteById(id);
        return CommonResult.result(isDelete);
    }

}
